package com.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.mall.common.constants.AliPayConstants;
import com.mall.common.constants.Constants;
import com.mall.common.utils.Security;
import com.mall.controller.vo.OrderCategoryXse;
import com.mall.controller.vo.OrderVO;
import com.mall.controller.vo.ViewInfo;
import com.mall.dao.custom.CtCartMapper;
import com.mall.dao.custom.CtGoodsMapper;
import com.mall.dao.custom.CtOrderMapper;
import com.mall.dao.generator.GoodsMapper;
import com.mall.entity.Cart;
import com.mall.entity.Goods;
import com.mall.entity.Order;
import com.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * @author xyl
 * @date 2021-03-04 18:56
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CtOrderMapper orderMapper;
    @Autowired
    private CtCartMapper cartMapper;
    @Autowired
    private CtGoodsMapper goodsMapper;

    @Override
    public String cartToPay(List<Cart> carts) {
        float totalMoney = 0;
        Order order = new Order();
        String bh = UUID.randomUUID().toString().replaceAll("-", "");
        for (Cart cart : carts) {
            order.setCreateBy(Security.getCurrentUserId());
            order.setCount(cart.getCount());
            order.setCreateTime(new Date());
            order.setPrice(cart.getPrice());
            order.setGoodsId(cart.getGoodsId());
            order.setTotal(cart.getTotal());
            order.setAddressId(cart.getAddressId());
            //创建订单 , 待付款
            order.setOrderStatus(0);
            order.setOrderNumber(bh);
            int count1 = this.orderMapper.insert(order);
            int count2 = cartMapper.deleteByPrimaryKey(cart.getCartId());
            totalMoney += order.getTotal();
        }
        return toPay(bh, totalMoney);
    }

    @Override
    public String orderToPay(List<Order> orders) {
        float totalMoney = 0;
        for (Order order : orders) {
            order.setCreateBy(Security.getCurrentUserId());
            order.setCreateTime(new Date());
            totalMoney += order.getTotal();
        }
        return toPay(orders.get(0).getOrderNumber(), totalMoney);
    }

    private String toPay(String bh, float totalMoney) {
        // 构建支付数据信息
        Map<String, String> data = new HashMap<>();
        //订单标题
        data.put("subject", "请进行支付");
        //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
        data.put("out_trade_no", bh);
        //该笔订单允许的最晚付款时间
        data.put("timeout_express", "1h");
        //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        data.put("total_amount", new DecimalFormat(".00").format(totalMoney) + "");
        //销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
        data.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //构建客户端
        DefaultAlipayClient alipayRsa2Client = new DefaultAlipayClient(
                AliPayConstants.gatewayUrl,
                AliPayConstants.app_id,
                AliPayConstants.merchant_private_key,
                "json",
                AliPayConstants.charset,
                AliPayConstants.alipay_public_key,
                AliPayConstants.sign_type);
        /*APP支付*/
//        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        /*网页支付*/
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        /*移动h5*/
//        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(AliPayConstants.ALI_NOTIFY_URL);
        request.setReturnUrl(AliPayConstants.ALI_RETURN_URL);
        request.setBizContent(JSON.toJSONString(data));
        String response = null;
        try {
            response = alipayRsa2Client.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return response;
    }

    @Override
    public List<Order> getOrderByNumber(String orderNumber) {
        return orderMapper.selectByOrderNumber(orderNumber);
    }

    @Override
    public int modifyStatusByOrderNumber(String orderNumber, int status) {
        return orderMapper.updateStatusByOrderNumber(orderNumber, status);
    }

    @Override
    public List<OrderVO> listVO(Order order) {
        return orderMapper.selectListVO(order);
    }

    @Override
    public Order getOrderByGoodsIdAndUserId(Integer goodsId, Integer currentUserId) {
        return orderMapper.selectByGoodsIdAndUserId(goodsId, currentUserId);
    }

    @Override
    public int add(Order order) {
        order.setCreateBy(Security.getCurrentUserId());
        order.setCreateTime(new Date());
        return orderMapper.insert(order);
    }

    @Override
    public int modifyAddressByOrderNumber(Integer addressId, String orderNumber) {
        return orderMapper.updateAddressByOrderNumber(addressId, orderNumber);
    }

    @Override
    public ViewInfo getViewInfo() {
        ViewInfo v1 = orderMapper.getTodayData();
        ViewInfo v2 = orderMapper.getTotalData();
        v1.setTotalDds(v2.getTotalDds());
        v1.setTotalXse(v2.getTotalXse());
        return v1;
    }

    @Override
    public Map<String, Float> getOrderCategoryXse() {
        Map<String, Float> map = new HashMap<>(10);
        List<OrderVO> orders = orderMapper.selectListVO(null);
        orders.forEach(o -> {
            if (map.containsKey(o.getCategoryName())) {
                float temp = map.get(o.getCategoryName()) + o.getTotal();
                map.put(o.getCategoryName(),temp) ;
            }else{
                map.put(o.getCategoryName(),o.getTotal());
            }
        });
        return map;
    }

    @Async("taskExecutor")
    @Override
    public void notifyOrder(String orderNumber) {
        List<Order> list = orderMapper.selectByOrderNumber(orderNumber);
        for (Order order : list) {
            cartMapper.deleteByGoodsIdAndUserId(order.getGoodsId(), Security.getCurrentUserId());
        }
        //修改订单状态
        orderMapper.updateStatusByOrderNumber(orderNumber, Constants.ORDER_STATUS_1);
        //修改销量和库存
        goodsMapper.updateXlAndKcByOrderNumber(orderNumber);
    }
}
